package com.mixed;

import javax.servlet.*;
import javax.servlet.http.*;
import com.mixed.*;
import java.io.*;
import javax.servlet.annotation.*;
import java.sql.*;

@MultipartConfig
public class Encrypt extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
            //response.setContentType("charset=utf-8");
            request.setCharacterEncoding("utf-8");
            String sender = request.getParameter("ensender");
            String receiver = request.getParameter("enreceiver");
            String SavePath = getServletContext().getRealPath("/WEB-INF/uploadEncrypt");//存储上传的公钥与明文并进行操作
            String TmpPath = SavePath + "/" + receiver + "_" + sender;//为用户创建一个临时目录，完成后就删除
            File TmpDir = new File(TmpPath);
            if(!TmpDir.exists())
                TmpDir.mkdirs();
            //Part keypart = request.getPart("publickey");改为从数据库读
            Part plainpart = request.getPart("plain");
            //String keypath = TmpPath + "/" + getfilename(keypart);
            String plainpath = TmpPath + "/" + "PlainMessage.dat";
            //keypart.write(keypath);
            plainpart.write(plainpath);
            try{
                String publickey = Mysql.readFromMYSQL(receiver);
                String[] result = MixedEncrypt.mixedEncryptWithKey(publickey, plainpath, TmpPath);
                Mail.sendMail(receiver, result, sender + " 发送给你密文与加密后的密钥", new String[]{"CipherFile.dat", "EncryptedDESkey.dat"});
            }catch(Exception e) {
                e.printStackTrace();
            }
            File tdir = new File(TmpPath);
            File[] child = tdir.listFiles();
            for(int i = 0; i < child.length; i++)
                child[i].delete();
            tdir.delete();
        }

    private static String getfilename(Part part) {
        String header = part.getHeader("Content-Disposition");
		int start = header.lastIndexOf("=");
        String fileName = header.substring(start + 1).replace("\"", "");
        return fileName;
    }
}
